<html>
 <head>
  <meta charset="UTF-8">
 </head>
 <body>
  <h1 data-lake-id="Jftv0" id="Jftv0"><span data-lake-id="u1083b742" id="u1083b742">典型回答</span></h1>
  <p data-lake-id="ub75d1fa1" id="ub75d1fa1"><br></p>
  <p data-lake-id="u075e2260" id="u075e2260"><span data-lake-id="ubcaac21f" id="ubcaac21f">想要保证多线程情况下，i++的正确性，需要考虑可见性、原子性及有序性。</span></p>
  <p data-lake-id="u87f508af" id="u87f508af"><span data-lake-id="u366c71ed" id="u366c71ed">​</span><br></p>
  <p data-lake-id="u253e33f6" id="u253e33f6"><span data-lake-id="u2a701b8b" id="u2a701b8b">在并发编程中，我们能用到的并发工具无非就是synchronized，volatile，reentrantLock以及并发工具类如AtomicInteger等。</span></p>
  <p data-lake-id="u11095526" id="u11095526"><span data-lake-id="ueccf55a9" id="ueccf55a9">​</span><br></p>
  <p data-lake-id="ubd9733a6" id="ubd9733a6"><span data-lake-id="u97352167" id="u97352167">这里面，除了volatile不可以以外（因为他没办法保证原子性），其他几种方式都可以。</span></p>
  <p data-lake-id="u1a307683" id="u1a307683"><span data-lake-id="ubbf68ddf" id="ubbf68ddf">​</span><br></p>
  <p data-lake-id="u63571ff0" id="u63571ff0"><br></p>
  <p data-lake-id="uf448548a" id="uf448548a"><span data-lake-id="u07df3481" id="u07df3481">使用 AtomicInteger 类：</span></p>
  <p data-lake-id="ucf89d2f8" id="ucf89d2f8"><span data-lake-id="u3366cb17" id="u3366cb17">​</span><br></p>
  <pre lang="java"><code>
private static AtomicInteger i = new AtomicInteger(0);

public static void increment() {
    i.incrementAndGet();
}
</code></pre>
  <p data-lake-id="udcd2c28f" id="udcd2c28f"><br></p>
  <p data-lake-id="u673ae4e6" id="u673ae4e6"><span data-lake-id="ue129c614" id="ue129c614">使用synchronized：</span></p>
  <p data-lake-id="ua3e21ac9" id="ua3e21ac9"><span data-lake-id="u4c6e2b52" id="u4c6e2b52">​</span><br></p>
  <pre lang="java"><code>
public class HollisTest{
    private static int i = 0;

    public void increment() {
        synchronized (HollisTest.class) {
            i++;
        }
    }
}

</code></pre>
  <p data-lake-id="udd772158" id="udd772158"><br></p>
  <p data-lake-id="u0fcf04ce" id="u0fcf04ce"><span data-lake-id="u550e6d99" id="u550e6d99">使用reentrantLock：</span></p>
  <p data-lake-id="u961bca8e" id="u961bca8e"><span data-lake-id="u2db27e9a" id="u2db27e9a">​</span><br></p>
  <pre lang="java"><code>
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class HollisTest {
    private int i = 0;
    private Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            i++;
        } finally {
            lock.unlock();
        }
    }
}

</code></pre>
 </body>
</html>